package com.zxl.yjb.activity.home.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.PoiItem;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.zxl.yjb.R;
import com.zxl.yjb.activity.home.position.PositionActivity;
import com.zxl.yjb.activity.my.MyFriendsActivity;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.FileUploadBean;
import com.zxl.yjb.bean.LocationBean;
import com.zxl.yjb.bean.OrderBean;
import com.zxl.yjb.bean.VoiceUploadBean;
import com.zxl.yjb.fragment.near.MultifunctionalInputFragment;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.PickerViewUtils;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.ToastUtils;
import com.zxl.yjb.widget.EaseVoiceRecorderView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderCreateActivity extends BaseActivity {


    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_page_title)
    TextView tv_page_title;
    @BindView(R.id.tv_service_type)
    TextView tv_service_type;
    @BindView(R.id.tv_end_time)
    TextView tv_end_time;
    @BindView(R.id.tv_position)
    TextView tv_position;
    @BindView(R.id.tv_people_focus)
    TextView tv_people_focus;
    @BindView(R.id.tv_people_near)
    TextView tv_people_near;
    @BindView(R.id.voice_recorder)
    EaseVoiceRecorderView voice_recorder;
    @BindView(R.id.ll_service_type)
    LinearLayout ll_service_type;
    @BindView(R.id.ll_time_end)
    LinearLayout ll_time_end;
    @BindView(R.id.ll_position)
    LinearLayout ll_position;
    @BindView(R.id.ll_focus)
    LinearLayout ll_focus;
    @BindView(R.id.ll_around)
    LinearLayout ll_around;

    private MultifunctionalInputFragment fragment;

    private DataManager dataManager;

    private String weizhi = "";
    private double longitude;
    private double latitude;
    private String phone = "";
    private String cat_id = "";
    private String cat_type = "";
    private String order_amount = "";
    private String start_time = "";
    private int end_time;
    private String orign_remark = "";
    private String Voice = "";
    private String Picture = "";
    private String friend_or_match_uid = "";

    private String name = "";


    private static final int REQUEST_SERVICETYPE = 111;
    private static final int REQUEST_POSITION = 112;
    private static final int REQUEST_FOCUS_PEOPLE = 113;
    private static final int REQUEST_NEARBY_PEOPLE = 114;

    private LocationBean locationBean;
    private List<String> time = new ArrayList<>();//这俩一定得对上
    private List<String> timeStr = new ArrayList<>();
    private String tempVoicePath = "";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_create);
        ButterKnife.bind(this);
        time.add("30");
        time.add("60");
        time.add("120");
        time.add("480");
        time.add("360");
        time.add("720");
        time.add("1440");

        timeStr.add("30分钟");
        timeStr.add("1小时");
        timeStr.add("2小时");
        timeStr.add("4小时");
        timeStr.add("6小时");
        timeStr.add("12小时");
        timeStr.add("24小时");

        end_time = 120;//默认两小时
        tv_end_time.setText("2小时");

        cat_id = getIntent().getStringExtra("id");
        cat_type = getIntent().getStringExtra("pid");
        name = getIntent().getStringExtra("name");

        initDefaultLocation();
        initView();
    }

    @Override
    protected void initView() {
        tv_page_title.setText("发单");
        tv_position.setText(weizhi);
        tv_service_type.setText(name);
        initFragment(voice_recorder);
    }


    private void initFragment(EaseVoiceRecorderView voiceRecorderView) {
        FragmentManager manager = getSupportFragmentManager();
        fragment = (MultifunctionalInputFragment) manager.findFragmentById(R.id.input_fragment);
        fragment.bindVoiceRecorderView(voiceRecorderView);
        fragment.btnSubmit.setText("发单");
        EditText editText = fragment.getEdittext();
        if (editText!=null)
        {
            editText.setHint("请输入发单内容（非必填）");
        }
        fragment.setOnInputViewItemClickListener(new MultifunctionalInputFragment.OnInputCompleteListener() {
            @Override
            public void onSubmitButtonClick(String content, List<LocalMedia> imgPath, String voiceFilePath) {
                orign_remark = content;
                tempVoicePath = voiceFilePath;


                if ("".equals(cat_id)||"".equals(cat_type)||"".equals(name))
                {
                    ToastUtils.show(OrderCreateActivity.this,"请选择服务类型");
                    return;
                }
                if (end_time == 0)
                {
                    ToastUtils.show(OrderCreateActivity.this,"请选择服务截止时间");
                    return;
                }
                /*if (TextUtils.isEmpty(orign_remark))
                {
                    ToastUtils.show(OrderCreateActivity.this,"请选输入发单内容");
                    return;
                }*/


                if (imgPath!=null&&imgPath.size()!=0)
                {
                    uploadPic(imgPath);
                }
                else if(!TextUtils.isEmpty(tempVoicePath))
                {
                    uploadVoice(tempVoicePath);
                }
                else
                {
                    createOrder();
                }

            }
        });
    }


    private void initDefaultLocation()
    {
        locationBean = (LocationBean) SaveBeanUtil.getBean(this, Const.LOCATION_LNGLAT);
        if (locationBean != null) {
            longitude = locationBean.getLng();
            latitude = locationBean.getLat();
            weizhi = locationBean.getStreet();
        }

        getLocation();
    }


    private void getLocation() {
        AMapLocationClient  mlocationClient = new AMapLocationClient(this);
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        if (isFinishing()) {
                            return;
                        }
                        //定位成功回调信息，设置相关消息
                        LocationBean locationBean = new LocationBean();
                        locationBean.setLat(amapLocation.getLatitude());
                        locationBean.setLng(amapLocation.getLongitude());
                        locationBean.setCountry(amapLocation.getCountry());
                        locationBean.setProvince(amapLocation.getProvince());
                        locationBean.setCity(amapLocation.getCity());
                        locationBean.setDistrict(amapLocation.getDistrict());
                        locationBean.setStreet(amapLocation.getStreet());
                        locationBean.setAddress(amapLocation.getAddress());
                        locationBean.setCitycode(amapLocation.getCityCode());
                        locationBean.setAdCode(amapLocation.getAdCode());
                        longitude = locationBean.getLng();
                        latitude = locationBean.getLat();
                        weizhi = locationBean.getStreet();
                        tv_position.setText(weizhi);
                        SaveBeanUtil.putBean(getApplicationContext(),Const.LOCATION_LNGLAT,locationBean);

                    }
                }
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setOnceLocation(true);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setLocationCacheEnable(false);
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
    }



    private void uploadPic(List<LocalMedia> imgPath)
    {
        dataManager = new DataManager();
        ObserverOnNextListener<FileUploadBean> listener = new ObserverOnNextListener<FileUploadBean>() {
            @Override
            public void onNext(FileUploadBean fileUploadBean) {
                haneldPicPath(fileUploadBean);
                if (!TextUtils.isEmpty(tempVoicePath))
                {
                    uploadVoice(tempVoicePath);
                }
                else
                {
                    createOrder();
                }

            }
        };
        dataManager.uploadMultiPicture(new ProgressObserver<FileUploadBean>(listener,this),imgPath);
    }


    private void uploadVoice(String path)
    {
        dataManager = new DataManager();
        ObserverOnNextListener<VoiceUploadBean> listener = new ObserverOnNextListener<VoiceUploadBean>() {
            @Override
            public void onNext(VoiceUploadBean voiceUploadBean) {
                Voice = voiceUploadBean.getYy_url();
                createOrder();
            }
        };
        dataManager.uploadVoice(new ProgressObserver<VoiceUploadBean>(listener,this),path);
    }

    private void haneldPicPath(FileUploadBean fileUploadBean)
    {
        Picture = "";
        ArrayList<String> picList = fileUploadBean.getUrls();
        if (picList!=null&&picList.size()>0)
        {
            for (int i = 0; i < picList.size(); i++) {
                Picture+=picList.get(i)+",";
            }
        }
        if (Picture.length()>0)
        {
            Picture = Picture.substring(0,Picture.length()-1);
        }

    }


    private void createOrder() {
        dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("weizhi", weizhi);
        map.put("longitude", longitude+"");
        map.put("latitude", latitude+"");
        map.put("phone", phone);
        map.put("cat_id", cat_id+"");
        map.put("cat_type", cat_type+"");
        map.put("order_amount", "");
        map.put("start_time", (new SimpleDateFormat("yyyy-MM-dd HH:mm")).format(new Date())+"");
        map.put("end_time", end_time*60+"");
        map.put("orign_remark", orign_remark);
        map.put("voice", Voice);
        map.put("picture", Picture);
        map.put("friend_or_match_uid", friend_or_match_uid);
        ObserverOnNextListener<OrderBean> listener = new ObserverOnNextListener<OrderBean>() {
            @Override
            public void onNext(OrderBean orderBean) {
                ToastUtils.show(getApplicationContext(), "发单成功");
                finish();
            }
        };
        dataManager.createOrder(new ProgressObserver<OrderBean>(listener, this), map);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST: // 图片选择结果回调
                    fragment.onActivityResult(requestCode, resultCode, data);
                    break;
                case REQUEST_SERVICETYPE:
                    cat_id = data.getStringExtra("id");
                    cat_type = data.getStringExtra("pid");
                    tv_service_type.setText(data.getStringExtra("name"));
                    break;

                case REQUEST_POSITION:
                    PoiItem poiItem = data.getParcelableExtra("position");
                    if (poiItem!=null)
                        tv_position.setText(poiItem.getTitle());
                        weizhi = poiItem.getTitle();
                        longitude = poiItem.getLatLonPoint().getLongitude();
                        latitude = poiItem.getLatLonPoint().getLatitude();
                    break;

                case REQUEST_FOCUS_PEOPLE:
                    friend_or_match_uid = "";
                    int userCount = data.getIntExtra("userCount",0);
                    friend_or_match_uid = data.getStringExtra("userList");
                    tv_people_focus.setText("已选择"+userCount+"个接单人");
                    tv_people_near.setText("");
                    break;

                case REQUEST_NEARBY_PEOPLE:
                    friend_or_match_uid = "";
                    int userCount2 = data.getIntExtra("userCount",0);
                    friend_or_match_uid = data.getStringExtra("userList");
                    tv_people_near.setText("已选择"+userCount2+"个接单人");
                    tv_people_focus.setText("");
                    break;
            }
        }
    }

    @OnClick({R.id.iv_back,R.id.ll_service_type, R.id.ll_time_end, R.id.ll_position, R.id.ll_focus, R.id.ll_around})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_service_type:
                Intent intent = new Intent(getApplicationContext(),ServiceSelectActivity.class);
                startActivityForResult(intent,REQUEST_SERVICETYPE);
                break;

            case R.id.ll_time_end:
                PickerViewUtils.customOptionPickerView(timeStr, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        end_time = Integer.parseInt(time.get(options1));
                        tv_end_time.setText(timeStr.get(options1));
                    }
                });
                break;

            case R.id.ll_position:
                Intent intent1 = new Intent(getApplicationContext(), PositionActivity.class);
                intent1.putExtra("origin","OrderCreateActivity");
                startActivityForResult(intent1,REQUEST_POSITION);
                break;

            case R.id.ll_focus:
                if (TextUtils.isEmpty(cat_id))
                {
                    ToastUtils.show(OrderCreateActivity.this,"请先选择服务类型");
                    return;
                }
                Intent intent2 = new Intent(OrderCreateActivity.this, MyFriendsActivity.class);
                intent2.putExtra("origin","Friends");
                intent2.putExtra("cat_id",cat_id);
                startActivityForResult(intent2,REQUEST_FOCUS_PEOPLE);
                break;

            case R.id.ll_around:
                if (TextUtils.isEmpty(cat_id))
                {
                    ToastUtils.show(OrderCreateActivity.this,"请先选择服务类型");
                    return;
                }
                Intent intent3 = new Intent(OrderCreateActivity.this, MyFriendsActivity.class);
                intent3.putExtra("origin","Around");
                intent3.putExtra("cat_id",cat_id);
                intent3.putExtra("longitude",longitude);
                intent3.putExtra("latitude",latitude);
                startActivityForResult(intent3,REQUEST_NEARBY_PEOPLE);
                break;
        }
    }
}
